package com.javajun.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.javajun.entity.SysRole;
import com.javajun.entity.SysUser;
import com.javajun.repository.SysUserRepository;

@Service
public class SysUserService implements UserDetailsService{

    @Autowired
    private SysUserRepository sysUserRepository;
    
    // Security 获取当前登录用户
    public UserDetails getCurrentUser() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        return userDetails;
    }
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户
        SysUser user = sysUserRepository.findByUsername(username);
        
        // 如果用户不存在，则抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + " 不存在");
        }
        // 获取用户角色
        List<SysRole> roles = user.getSysRole();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getCode()));
        }
        
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    public SysUser findByEmail(String email) {
        return sysUserRepository.findByEmail(email);
    }

    public SysUser findByUsername(String username) {
        return sysUserRepository.findByUsername(username);
        
    }
    
    public SysUser findById(Integer id) {
        Optional<SysUser> optional = sysUserRepository.findById(id);
        SysUser sysUser = new SysUser();
        if(optional.isPresent()) {
            sysUser = optional.get();
        }
        return sysUser;
    }

}
